package com.liunian.compress.impl;

import com.liunian.compress.Compressor;
import com.liunian.exceptions.CompressException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 使用Gzip算法进行压缩的具体实现。
 */
@Slf4j
public class GzipCompressor implements Compressor {
    @Override
    public byte[] compress(byte[] bytes) {
        // 本质就是，将buf作为输入，将结果输出到另一个字节数组中
        try (
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)
        ) {
            gzipOutputStream.write(bytes);
            gzipOutputStream.finish();
            byte[] result = baos.toByteArray();
            if (log.isDebugEnabled()) {
                log.debug("对字节数组进行压缩长度由[{}]压缩至[{}]", bytes.length, result.length);
            }
            return result;
        } catch (IOException e) {
            log.error("对字节数组进行压缩时发生异常。", e);
            throw new CompressException(e);
        }
    }

    @Override
    public byte[] deCompress(byte[] bytes) {

        try (
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                GZIPInputStream gzipInputStream = new GZIPInputStream(bais)
        ) {

            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = gzipInputStream.read(buf)) != -1) {
                out.write(buf,0,len);
            }
            byte[] result = out.toByteArray();
            if (log.isDebugEnabled()) {
                log.debug("对字节数组进行解压缩长度由[{}]变为[{}]", bytes.length, result.length);
            }
            return result;
        } catch (IOException e) {
            log.error("对字节数组进行解压缩时发生异常。", e);
            throw new CompressException(e);
        }
    }
}
